package com.lzxuni.modules.disease.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.utils.FileUtil;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.common.utils.date.DateUtil;
import com.lzxuni.modules.basics.entity.BasicTree;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.common.entity.PageData;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.common.service.FileEntityService;
import com.lzxuni.modules.disease.entity.DiseaseInformation;
import com.lzxuni.modules.disease.entity.DiseaseManagement;
import com.lzxuni.modules.disease.service.DiseaseInformationService;
import com.lzxuni.modules.disease.service.DiseaseManagementService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 病情管理 前端控制器
 * </p>
 *
 * @author gyl
 * @since 2020-12-02
 */
@RestController
    @RequestMapping("/Disease/diseaseManagement")
public class DiseaseViewController extends BaseController {

    @Autowired
    private DiseaseManagementService diseaseManagementService;
    @Autowired
    private DiseaseInformationService diseaseInformationService;

    private String templatesPath="/Disease/diseaseManagement";
    private static String typeName = "病情管理上传图片";
    private static String ywType = "diseaseman_img";

    @Autowired
    private FileEntityService fileEntityService;

    //主页面
    @RequestMapping("/Index")
    public ModelAndView Index() {
        ModelAndView mv = new ModelAndView("/Disease/diseaseManagement/index");
        return mv;
    }

    //查询数据
    @RequestMapping("/GetList")
    public Object GetList(String pagination,String queryJson){
        PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
        DiseaseManagement diseaseManagement = JSON.parseObject(queryJson, DiseaseManagement.class);
        PageData pageData = getPageData(diseaseManagementService.queryPage3(pageParameter, diseaseManagement));
        return R.ok().put("data", pageData);
    }


    //表单页
    @RequestMapping("/Form")
    public ModelAndView Form(String keyValue,String queryJson) throws Exception{
        ModelAndView mv = new ModelAndView("/Disease/diseaseManagement/form");
        BasicTree basicTree = JSON.parseObject(queryJson, BasicTree.class);
        mv.addObject("basicTree", basicTree);
        FileEntity fileBeanCustom = new FileEntity();
        fileBeanCustom.setYwId(keyValue);
        fileBeanCustom.setYwType(ywType);
        mv.addObject("imgCount", fileEntityService.queryNumByFileEntity(fileBeanCustom));
        mv.addObject("id", keyValue);
        DiseaseManagement diseaseManagement = diseaseManagementService.getById(keyValue);
        List<DiseaseInformation> InforList = diseaseInformationService.list(new QueryWrapper<DiseaseInformation>().eq("disease_id", keyValue).orderByAsc("create_time"));
        if(InforList.size()>0){
            mv.addObject("type", "edit");
            mv.addObject("pestDetaList", InforList);
            mv.addObject("detailCoount",InforList.size());
        }else{
            mv.addObject("type", "add");
        }
//        List<FileEntity> fileEntities = fileEntityService.queryListByFileEntity(fileBeanCustom);
//        mv.addObject("fileEntities", fileEntities);
//
//        mv.addObject("disShuju", diseaseManagement);
        return mv;
    }


    @RequestMapping("/SaveForm")
    public Object insertDo(String keyValue, DiseaseManagement diseaseManagement, DiseaseInformation pestDetails, String subJson,String diseaseman_imgs) throws Exception{
        List<DiseaseInformation> pestDetailList= JSON.parseArray(subJson, DiseaseInformation.class);
        if(StringUtils.isEmpty(keyValue)){
            String ywId = UuidUtil.get32UUID();
            if (!com.lzxuni.common.utils.StringUtils.isEmpty(diseaseman_imgs) && !"&amp;nbsp;".equals(diseaseman_imgs)) {
                fileEntityService.insert(diseaseman_imgs.replace("&quot;", "\""), ywId, typeName, ywType, null);
            }
            int temp = 0;
            for(DiseaseInformation disinfo :pestDetailList ){
                disinfo.setDiseaseId(ywId);
                disinfo.setCreateTime(new Date());
                if(disinfo.getStatusFs().equals("1")){
                    temp++;
                }
            }
            if(temp > 0){
                diseaseManagement.setIshavedis("1");//预警表示
            }else{
                diseaseManagement.setIshavedis("0");
            }
            diseaseManagement.setIsedit("0");//不编辑表示
            diseaseManagement.setDiseaseId(ywId);
            diseaseManagement.setLandId(diseaseManagement.getLandId());
            diseaseManagement.setCreateTime(diseaseManagement.getCreateTime());
            diseaseManagementService.save(diseaseManagement);
            diseaseInformationService.saveBatch(pestDetailList);
            return R.ok("保存成功");
        }else{
            fileEntityService.deleteByYwId(keyValue);
            if (!StringUtils.isEmpty(diseaseman_imgs) && !"&amp;nbsp;".equals(diseaseman_imgs)) {
                fileEntityService.insert(diseaseman_imgs.replace("&quot;", "\""), keyValue, typeName, ywType, null);
            }
            diseaseInformationService.remove(new QueryWrapper<DiseaseInformation>().eq("disease_id",keyValue));
            int temp = 0;
            for(DiseaseInformation disinfo :pestDetailList ){
                disinfo.setDiseaseId(keyValue);
                disinfo.setCreateTime(new Date());
                if(disinfo.getStatusFs().equals("1")){
                    temp++;
                }
            }
//             diseaseManagement = diseaseManagementService.getById(keyValue);
            diseaseManagement.setDiseaseId(keyValue);
            diseaseManagement.setIsedit("1");//编辑表示
            diseaseManagement.setCreateTime(diseaseManagement.getCreateTime());
            if(temp > 0){
                diseaseManagement.setIshavedis("1");//是病情表示
            }else{
                diseaseManagement.setIshavedis("0");
            }
            diseaseManagementService.updateById(diseaseManagement);
            diseaseInformationService.saveBatch(pestDetailList);
            return R.ok("修改成功");
        }
    }

    //删除数据
    @RequestMapping("/DeleteForm")
    public Object delete(String keyValue) {
        diseaseManagementService.removeById(keyValue);
        fileEntityService.deleteByYwId(keyValue);
        diseaseInformationService.remove(new QueryWrapper<DiseaseInformation>().eq("disease_id",keyValue));
        return R.ok("删除成功");
    }


    //主页导出
    @RequestMapping("/exportExcel")
    public void exportExcel3(HttpServletResponse response, String queryJson, HttpServletRequest request) throws IOException {
        DiseaseManagement diseaseManagement = JSON.parseObject(queryJson, DiseaseManagement.class);

        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "病情管理信息" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = diseaseManagementService.exportExcel3(diseaseManagement);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

    //详情信息列表页面
    @RequestMapping("/IndexDis")
    public ModelAndView IndexSzxx(String diseaseId) {
        ModelAndView mv = new ModelAndView("/Disease/diseaseManagement/indexdis");
        mv.addObject("diseaseId", diseaseId);

        return mv;
    }
    //查询数据
    @RequestMapping("/GetListDis")
    public Object GetListszxx(String pagination,String queryJson,String diseaseId){
        PageParameter pageParameter = JSON.parseObject(pagination, PageParameter.class);
        DiseaseManagement diseaseManagement = JSON.parseObject(queryJson, DiseaseManagement.class);
//        DiseaseManagement diseaseManagement = new DiseaseManagement();
//        diseaseManagement.setDiseaseId(diseaseId);
        PageData pageData = getPageData(diseaseManagementService.queryPage2(pageParameter, diseaseManagement));
        return R.ok().put("data", pageData);
    }
    //次页导出
    @RequestMapping("/exportExcel2")
    public void exportExcel2(HttpServletResponse response, String diseaseId, String information, HttpServletRequest request) throws IOException {
        DiseaseManagement diseaseManagement = new DiseaseManagement();
        diseaseManagement.setDiseaseId(diseaseId);
        if(StringUtils.isNotEmpty(information)){
            diseaseManagement.setInformation(information);
        }
        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "病情管理信息" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = diseaseManagementService.exportExcel2(diseaseManagement);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }


    //双击查看
    @RequestMapping("/QueryImg")
    public ModelAndView QueryImg(String keyValue) throws Exception {
        ModelAndView mv = new ModelAndView("/LR_Pest/pestmanagement/img");
        FileEntity fileBeanCustom = new FileEntity();
        fileBeanCustom.setYwId(keyValue);
        List<FileEntity> fileEntities = fileEntityService.queryListByFileEntity(fileBeanCustom);
        mv.addObject("fileEntities", fileEntities);
        return mv;
    }


    //月分析页面
    @RequestMapping("/IndexMonth")
    public ModelAndView IndexMonth() {
        ModelAndView mv = new ModelAndView("/Disease/diseaseManagement/index_month");
        return mv;
    }

    //月分析Echar图
    @RequestMapping("/DayEcharts")
    public Object getMothEcharts(String parentId,String beginDate,String endDate) {

        DiseaseManagement diseaseManagement= new DiseaseManagement ();
        diseaseManagement.setLandId(parentId);
        if(StringUtils.isNotEmpty(beginDate)){
            diseaseManagement.setBeginDate(beginDate);
        }
        if(StringUtils.isNotEmpty(endDate)){
            diseaseManagement.setEndDate(endDate);
        }
//        diseaseManagement.setLandId("fb11a3517f02ebbff6eaa99a9313e6fd");
        List<DiseaseManagement> list = diseaseManagementService.queryMList(diseaseManagement);
        System.out.println(list.toString());
        //List<DiseaseManagement> listGroup = diseaseManagementService.queryMonthListGroup(diseaseManagement);
        Map<String, List<DiseaseManagement>> map = new HashMap<>();
        Map<String, String> mapIn = new HashMap<>();
        int i=0;
        for(DiseaseManagement dm : list){
            if(StringUtils.isEmpty(dm.getDtype())){
                return R.error(401, "未查询到信息！");
            }
            dm.setDtime(new SimpleDateFormat("yyyy-MM-dd").format(dm.getCreateTime()));
            if(map.containsKey(dm.getDtype())){//map中存在此id，将数据存放当前key的map中
                map.get(dm.getDtype()).add(dm);
            }else{//map中不存在，新建key，用来存放数据
                List<DiseaseManagement> tmpList = new ArrayList<>();
                tmpList.add(dm);
                map.put(dm.getDtype(), tmpList);
                mapIn.put(i+"", dm.getDtype());
            }
            i++;
        }

        Map map0=new HashMap<>();
        map0.put("date",map);
        map0.put("mapkey",mapIn);
        return R.ok().put("data", JSON.toJSONString(map0));
    }

    //月分析导出
    @RequestMapping("/exportExcelMonth")
    public void exportExcelMonth(HttpServletResponse response,String parentId,String beginDate,String endDate,HttpServletRequest request) throws IOException {
        DiseaseManagement diseaseManagement = new DiseaseManagement();
        diseaseManagement.setLandId(parentId);
        if(StringUtils.isNotEmpty(beginDate)){
            diseaseManagement.setBeginDate(beginDate);
        }
        if(StringUtils.isNotEmpty(endDate)){
            diseaseManagement.setEndDate(endDate);
        }
        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "病情月分析" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = diseaseManagementService.exportExcelMonth(diseaseManagement);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

    //年分析页面
    @RequestMapping("/IndexYear")
    public ModelAndView IndexYear() {
        ModelAndView mv = new ModelAndView("/Disease/diseaseManagement/index_year");
        return mv;
    }
    //年分析Echar图
    @RequestMapping("/YearEcharts")
    public Object getYearEcharts(String parentId,String beginDate,String endDate) {
        DiseaseManagement diseaseManagement= new DiseaseManagement ();
        diseaseManagement.setLandId(parentId);
        if(StringUtils.isNotEmpty(beginDate)){
            diseaseManagement.setBeginDate(beginDate);
        }
        if(StringUtils.isNotEmpty(endDate)){
            diseaseManagement.setEndDate(endDate);
        }
//        diseaseManagement.setLandId("fb11a3517f02ebbff6eaa99a9313e6fd");
        List<DiseaseManagement> list = diseaseManagementService.queryYList(diseaseManagement);
        System.out.println(list.toString());
        //List<DiseaseManagement> listGroup = diseaseManagementService.queryMonthListGroup(diseaseManagement);
        Map<String, List<DiseaseManagement>> map = new HashMap<>();
        Map<String, String> mapIn = new HashMap<>();
        int i=0;
        for(DiseaseManagement dm : list){
            if(StringUtils.isEmpty(dm.getDtype())){
                return R.error(401, "未查询到信息！");
            }
            //dm.setDtime(new SimpleDateFormat("yyyy-MM").format(dm.getCreateTime()));
            dm.setDtime(dm.getDyear());
            if(map.containsKey(dm.getDtype())){//map中存在此id，将数据存放当前key的map中
                map.get(dm.getDtype()).add(dm);
            }else{//map中不存在，新建key，用来存放数据
                List<DiseaseManagement> tmpList = new ArrayList<>();
                tmpList.add(dm);
                map.put(dm.getDtype(), tmpList);
                mapIn.put(i+"", dm.getDtype());
            }
            i++;
        }

        Map map0=new HashMap<>();
        map0.put("date",map);
        map0.put("mapkey",mapIn);
        return R.ok().put("data", JSON.toJSONString(map0));
    }

    //年分析导出
    @RequestMapping("/exportExcelYear")
    public void exportExcelYear(HttpServletResponse response,String parentId,String beginDate,String endDate,HttpServletRequest request) throws IOException {
        DiseaseManagement diseaseManagement = new DiseaseManagement();
        diseaseManagement.setLandId(parentId);
        if(StringUtils.isNotEmpty(beginDate)){
            diseaseManagement.setBeginDate(beginDate);
        }
        if(StringUtils.isNotEmpty(endDate)){
            diseaseManagement.setEndDate(endDate);
        }
        //System.out.println(diseaseManagement.toString());
        BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
        String filename = "病情年分析" + DateUtil.DateToString(new Date(), "yyyyMMddHHmm") + ".xls";
        String agent = request.getHeader("User-Agent");
        filename = FileUtil.encodeDownloadFilename(filename, agent);
        String contentType = request.getSession().getServletContext().getMimeType(filename);
        response.setContentType(contentType);
        response.setHeader("content-disposition", "attchment;filename=" + filename);
        Workbook wb = null;
        try {
            wb = diseaseManagementService.exportExcelYear(diseaseManagement);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

}

